package com.happypets.servicesImpl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.happypets.daoImpl.PetDaoImpl;
import com.happypets.model.CartBean;
import com.happypets.model.UserBean;
import com.happypets.services.UserService;
import com.happypets.utils.DB;

public class UserServiceImpl implements UserService {
	
	PetDaoImpl dao = new PetDaoImpl();
//	DBUtils db = new DB();
	public UserBean getUserBeanById(String id) {
		String sql = "select a.* from vipinfo a where a.vip_id='"+id+"'";
		List<Map<String,String>> lm = (List<Map<String, String>>) dao.query(sql);
		
		return mapToBean(lm.get(0));
	}

	public UserBean getUserBeanByName(String name) {
		
		String sql = "select a.* from vipinfo a where a.vip_name='"+name+"'";
		
		List<Map<String,String>> lm = (List<Map<String, String>>) dao.query(sql);
		return mapToBean(lm.get(0));
		
	}

	public int login(String userName, String passwd) {
		
		String sql = "select * from vipinfo a where a.vip_name='"+userName+"'";
		String sql2 = "select * from vipinfo a where a.vip_password='"+passwd+"' and a.vip_id = (select a.vip_id from vipinfo a where a.vip_name='"+userName+"')";
		
		
		List<?> ln = dao.query(sql);
		List<?> lp = dao.query(sql2);
		
		Map<String,String> map = new HashMap<String,String>();
		
		if(ln.equals(lp)){
			return 1;
			
		}else{
//			failed
			
			if(ln == null || ln.size()<=0){
				return 2;
			}else{
				return 3;
			}
		}
	}
	
	private UserBean mapToBean(Map<String,String> map){
		
		UserBean ub = new UserBean();
		
		ub.setUserAddress(map.get("VIP_ADDRESS"));
		ub.setUserAge(map.get("VIP_AGE"));
		ub.setUserAllMoney(map.get("VIP_ALLMONEY"));
		ub.setUserBir(map.get("VIP_BIRTHDAY"));
		ub.setUserEmail(map.get("VIP_EMAIL"));
		ub.setUserId(map.get("VIP_ID"));
		ub.setUserName(map.get("VIP_NAME"));
		ub.setUserPhone(map.get("VIP_PHONE"));
		ub.setUserSex(map.get("VIP_SEX"));
		ub.setPassword(map.get("VIP_PASSWORD"));
		ub.setUserAddPro(map.get("VIP_ADD_PRO"));
		ub.setUserAddCity(map.get("VIP_ADD_CITY"));
		ub.setUserAddCou(map.get("VIP_ADD_COU"));
		ub.setUserRealName(map.get("VIP_REALNAME"));
		ub.setUserPhoto(map.get("VIP_PHOTO"));
		
		return ub;
		
	}

	public int addUser(UserBean user) {
		
		String name = user.getUserName();
		String passwd = user.getPassword();
		String sex = user.getUserSex();
		String phone = user.getUserPhone();
		String email = user.getUserEmail();
		String address = user.getUserAddress();
		String pro = user.getUserAddPro();
		String city = user.getUserAddCity();
		String cou = user.getUserAddCou();
//		String realName = user.getUserRealName();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String sql = "insert into vipinfo(vip_id,vip_name,vip_password,vip_grage,vip_allMoney,vip_sex,vip_phone,vip_email,vip_add_pro,vip_add_city,vip_add_cou,vip_address,vip_registdate) "
				+ "values(vipinfo_seq.nextval,'"+name+"','"+passwd+"',1,'0.00','"+sex+"','"+phone+"','"+email+"','"+pro+"','"+city+"','"+cou+"','"+address+"',to_date('"+sdf.format(new Date())+"','YYYY-MM-DD HH24:MI:SS'))";
//		dao.query(sql);
		
//		return db.executeSql(sql)?1:0;
		return dao.excutQuery(sql);
	}
	
	
	public int updateUser(UserBean user){
		String id = user.getUserId();
		String name = user.getUserName();
		String passwd = user.getPassword();
		String sex = user.getUserSex();
		String phone = user.getUserPhone();
		String email = user.getUserEmail();
		String address = user.getUserAddress();
		String pro = user.getUserAddPro();
		String city = user.getUserAddCity();
		String cou = user.getUserAddCou();
		String realName = user.getUserRealName();
		String bir = user.getUserBir();
		
		String sql = "update vipinfo a set "
				+"a.vip_name='"+name+"',"
				+ "a.vip_sex='"+sex+"',"
				+ "a.vip_age=2,"
				+ "a.vip_birthday=to_date('"+bir+"','yyyy-mm-dd'),"
				+ "a.vip_address='"+address+"',"
				+ "a.vip_password='"+passwd+"',"
				+ "a.vip_email='"+email+"',"
				+ "a.vip_phone='"+phone+"',"
//				+ "a.vip_photo='"++"',"
				+ "a.vip_add_pro='"+pro+"',"
				+ "a.vip_add_city='"+city+"',"
				+ "a.vip_add_cou='"+cou+"',"
				+ "a.vip_realname='"+realName+"' "
				+ "where a.vip_id="+id;
		
		return dao.excutQuery(sql);
		
	}
	
	
	public int updateUserPhoto(UserBean user){
		String id = user.getUserId();
		String photo = user.getUserPhoto();

		
		String sql = "update vipinfo a set "
				+ "a.vip_photo='"+photo+"'"
				+ "where a.vip_id="+id;
		System.out.println(sql);
//		return db.executeSql(sql)?1:0;
		return dao.excutQuery(sql);
		
	}
	
	/**
	 * 获取单个宠物的信息
	 * @param id
	 * @return
	 */
	public List<Map<String,String>> getPetInfoById(String id){
		
		String sql = "select a.*,b.name,c.name from animalsinfo a "
				+ "left join bigcategory b on a.bigcategoryid=b.bigcategory "
				+ "left join smallcategory c on a.smallcategoryid = c.smallcategory where a.id="+id;
		
		return (List<Map<String, String>>) dao.query(sql);
		
	}
	
	
	/**
	 * 通过id获取账单信息
	 * @param id
	 * @return
	 */
	public List<?> UserShopInfoById(String id){
		String sql = "select d.animal_name,c.sale_money,c.sale_date,c.form_status from salehistory c left join animalsinfo d on c.animal_id = d.id where c.buyer_id = "+id;
		
		return dao.query(sql);
	}
	
	
	public int formDeal(String name,String phone, String address, String userId,String  allPrice,List<Map<String,String>> lm){
		
		for (int i = 0; i < lm.size(); i++) {
			
			Map<String,String> map = lm.get(i);
			String sqls[] = new String[3];
			sqls[0] = "update animalsinfo a set a.animal_saled = '0'  where a.id="+map.get("petId");
			System.out.println(sqls[0]);
			
			String sql = "select t.vip_allmoney, t.rowid from VIPINFO t where t.vip_id ="+userId;
			float userAllMoney = Float.parseFloat(dao.getString(sql));
			
			sqls[1] = "update vipinfo t set t.vip_allmoney = '"+(userAllMoney+Float.parseFloat(allPrice))+"'";
			System.out.println(sqls[1]);
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sqls[2] = "insert into salehistory(saled_id,animal_id,sale_money,buyer_id,sale_date,buyer_evaluate,people,phone,address,form_status)"
					+ "values( salehistory_seq.nextval,"+map.get("petId")+","+map.get("petPrice")+","+userId+",to_date('"+sdf.format(new Date())+"',"
							+ "'YYYY-MM-DD HH24:MI:SS'),1,'"+name+"','"+phone+"','"+address+"','未处理')";
			System.out.println(sqls[2] );
			
//			db.batching(sqls);
			dao.excuteBatch(sqls);
			
		}
		
		
		return 1;
	}
	
	/**
	 * 添加至购物车
	 * @param cart
	 * @return
	 */
	public int addToCart(CartBean cart){
		
		String userId = cart.getUserId();
		String petId = cart.getId();
		int count = cart.getCount();
		double price = cart.getPrice();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now = new Date();
		
		//is double
		
		String sql = "select a.pet_count from cart a where a.user_id="+userId+" and a.pet_id="+petId;
		
		String oldCount = dao.getString(sql);
		
		if(oldCount != null && !oldCount.equals("")){
			
			int newCount = count+Integer.parseInt(oldCount);
			
			sql="update cart a set a.pet_count="+newCount+"  where a.user_id="+userId+" and a.pet_id="+petId;
			System.out.println("添加到购物车"+sql);
			return dao.excutQuery(sql);
		}
		
		
		
		 sql = "insert into cart(id,user_id,pet_id,pet_count,pet_price,add_date,flag) "
				+ "values(cart_seq.nextval,"+userId+","+petId+","+count+","+price+",to_date('"+sdf.format(now)+"','YYYY-MM-DD HH24:MI:SS'),0)";
		System.out.println("添加购物车 "+sql);
		return dao.excutQuery(sql);
	}
	
	/**
	 * 删除商品
	 * @param cart
	 * @return
	 */
	public int delFromCart(CartBean cart){
		String userId = cart.getUserId();
		String petId = cart.getId();
		int count = cart.getCount();
		double price = cart.getPrice();
		
		String sql = "select a.pet_count from cart a where a.user_id="+userId+" and a.pet_id="+petId;
		String oldCount = dao.getString(sql);
		
		int newCount = Integer.parseInt(oldCount)-count;
		
		if(newCount <= 0){
			sql = "delete cart a where a.user_id="+userId+" and a.pet_id="+petId;
		}else{
			sql="update cart a set a.pet_count="+newCount+"  where a.user_id="+userId+" and a.pet_id="+petId;
		}
		
		System.out.println("删除购物车的数据："+sql);
		
		return dao.excutQuery(sql);
	}
	
	/**
	 * 清空
	 * @param cart
	 * @return
	 */
	public int emptyCart(CartBean cart){
		
		String userId = cart.getUserId();
		String sql = "delete from cart a where a.user_id="+userId;
		System.out.println("清空购物车："+sql);
		return dao.excutQuery(sql);
	}
	
	public List<CartBean> findCart(String userId){
		
		String sql ="select t.*,a.animal_image01,a.animal_name from CART t left join animalsinfo a on t.pet_id=a.id where t.user_id="+userId;
		
		List<Map<String,String>> lm = (List<Map<String, String>>) dao.query(sql);
		
		List<CartBean> carts = new ArrayList<CartBean>();
		
		for (int i = 0; i < lm.size(); i++) {
			
			CartBean cart = new CartBean();
			
			Map<String,String> map = lm.get(i);
			
			cart.setCount(Integer.parseInt(map.get("PET_COUNT")));
			cart.setId(map.get("PET_ID"));
			cart.setImage(map.get("ANIMAL_IMAGE01"));
			cart.setName(map.get("ANIMAL_NAME"));
			cart.setPrice(Double.parseDouble(map.get("PET_PRICE")));
			cart.setUserId(map.get("USER_ID"));
			
			carts.add(cart);
			
		}
		
		return carts;
	}
	
	/**
	 * 通过页数获取用户部分信息 
	 * 
	 * @param pageShowNumber
	 * @param currentPage
	 * @return vip_id,vip_name,vip_allmoney,vip_registdate
	 */
	public List<Map<String,String>> userInfoPage(int pageShowNumber,int currentPage){
		
		String sql = "select * from (select t.vip_id,t.vip_name,t.vip_allmoney,t.vip_registdate,rownum as rowno from vipinfo t where rownum<="+(currentPage * pageShowNumber)+") "
				+ "where rowno>"+((currentPage - 1) * pageShowNumber)+" order by vip_registdate desc";
		
//		System.out.println(sql);
		
		return (List<Map<String, String>>) dao.query(sql);
		
//		and rownum<="+(currentPageNumber * showNumber)+" ) where rownu>"+((currentPageNumber - 1) * showNumber);
		
	}
	
	
	/**
	 * 获取宠物的信息
	 * @param pageShowNumber
	 * @param currentPage
	 * @return
	 */
	public List<Map<String,String>> petInfoPage(int pageShowNumber,int currentPage){
		
		
		String sql = "select b.* from"
				+ "(select a.id,a.animal_nickname,a.animal_name,a.animal_sex,a.animal_color,a.animal_state,rownum as rowno from animalsinfo a where rownum<="+(currentPage * pageShowNumber)+") b "
				+ "where rowno>"+((currentPage - 1) * pageShowNumber);
		
//		System.out.println(sql);
		
		return (List<Map<String, String>>) dao.query(sql);
		
//		and rownum<="+(currentPageNumber * showNumber)+" ) where rownu>"+((currentPageNumber - 1) * showNumber);
		
	}
	
	
	
	/**
	 * 获取订单信息
	 * @param pageShowNumber
	 * @param currentPage
	 * @return
	 */
	public List<Map<String,String>> dealInfoPage(int pageShowNumber,int currentPage){
		
		String sql = "select a.*,v.vip_name from"
				+ " (select * from (select t.*,rownum as rowno from salehistory t order by t.sale_date desc ) where rownum <="+(currentPage * pageShowNumber)+") "
				+ " a left join vipinfo v on v.vip_id=a.buyer_id left join animalsinfo b on b.id=a.animal_id where rowno>"+((currentPage - 1) * pageShowNumber);
		
		System.out.println(sql);
		
		
		
		return (List<Map<String, String>>) dao.query(sql);
		
//		and rownum<="+(currentPageNumber * showNumber)+" ) where rownu>"+((currentPageNumber - 1) * showNumber);
		
	}
	
	/**
	 * 修改订单状态
	 * @param formId
	 * @param formStatus
	 * @param formDealer
	 * @return
	 */
	public int updateFormStatus(String formId,String formStatus,String formDealer){
		
		String sql = "update salehistory a set a.form_status='"+formStatus+"' ,a.form_dealer='"+formDealer+"' where a.saled_id="+formId;
		
		System.out.println(sql);
		
		return dao.excutQuery(sql);
	}
	
	
	/**
	 * 获取用户未评论的宠物列表
	 * @param userId
	 * @return
	 */
	public List<Map<String,String>> userNoComms(String userId){
		
		String sql = "select c.* from "
				+ "( select a.saled_id as aid,b.animal_name as aname,a.sale_date as adate ,"
				+ "a.form_status as sta from salehistory a  left join animalsinfo b on a.animal_id=b.id "
				+ "where a.buyer_id="+userId+" and a.form_status='已签收' ) c left join vipevaluates d on "
				+ "c.aid = d.id where d.evaluate_content is  NULL ";
		
		return (List<Map<String, String>>) dao.query(sql);
		
	}
	
	
	/**
	 * 添加评论
	 * @param id
	 * @param comment
	 * @param grade
	 * @return
	 */
	public int addComment(String id,String comment,String grade){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String sql = "insert into vipevaluates(id,evaluate_date,evaluate_content,evaluate_star) "+
							"values("+id+",to_date('"+sdf.format(new Date())+"','YYYY-MM-DD HH24:MI:SS'),'"+comment+"','"+grade+"')";
		
		System.out.println(sql);
		
		return dao.excutQuery(sql);
		
	}
	
	
	/**
	 * 登录
	 * 成功返回用户id
	 * @param userName
	 * @param passwd
	 * @return
	 */
	public String backstageUserLogin(String userName,String passwd){
		
		String sql = "select t.manager_id as id from managerinfo t where t.manager_name='"+userName+"' and t.manager_password = '"+passwd+"'";
		
		List<Map<String,String>> list = (List<Map<String, String>>) dao.query(sql);
		
		System.out.println("list "+list);
		
		if(list == null || list.size() <= 0){
			return "-1";
		}
		
		String id = list.get(0).get("ID");
		System.out.println(id);
		
		return id;
		
	}
	
	/**
	 * 获取用户权限
	 * @param id
	 * @return
	 */
	public List<Map<String,String>> getPowerSession(String id){
		
		String sql = "select t.power, t.rowid from POWER t where t.managerid="+id;
		
		return (List<Map<String, String>>) dao.query(sql);
		
	}
	
	/**
	 * 更改用户密码
	 * @param userName
	 * @param password
	 * @return
	 */
	public int updateUserPasswd(String userName,String password){
		
		String sql = "update vipinfo v set v.vip_password = '"+password+"' where v.vip_name='"+userName+"'";
		
		return dao.excutQuery(sql);
	}
	

}
